const path = require('path')
const multer = require('multer')
const express = require('express')
const apiAddr = require('../../config/PublicApi')
// 使用 uuid 来生成图片的唯一标识
const {v4} = require('uuid')
// 处理图片上传
const uploadImgFileApp = express()

// 创建文件存储的配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    if (file.mimetype.includes('image')) {
      cb(null, path.resolve(__dirname, '../../storage/images'))
    }
  },
  filename: (req, file, cb) => {
    cb(null, v4().replaceAll('-','') + '_' +  file.originalname)
  }
})
// 上传处理器的基础配置
const uploadParams = multer({storage})

// 上传的文件的配置信息
const uploadConfig = uploadParams.fields([
  {
    name: 'blogAvatars', // 跟前端的头像上传组件的 name 属性保持一致
    maxCount: 9 // 允许一次性上传数量
  }
])

// 接收图片的 api 的处理
uploadImgFileApp.post('/', uploadConfig, (req,res)=>{
  // 返回上传成功的信息 并且返回 保存到服务器中的文件名
  const data = []
  for (let i = 0; i < req.files.blogAvatars?.length; i++) {
    data.push(`${apiAddr.hostAddr + apiAddr.getImgApiAddr}/${req.files.blogAvatars[i].filename}`)
  }

  res.setHeader('Content-Type', 'application/json')
  res.send({
    status: 200,
    message:'upload success!',
    data:{
      imgList: data
    }
  })
})

module.exports = uploadImgFileApp